package com.star.caffeine.service;


import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description: test
 * @author: star
 * @create: 2025-04-23 17:11
 **/
@Component
public class TestService {

    private final LoadingCache<String, String> cache = Caffeine.newBuilder()
            .build(new CacheLoader<String, String>() {
                @Override
                // 该方法必须实现
                public String load(String k) throws Exception {
                    return "不存在, 返回default";
                }

                @Override
                // 如果需要批量加载
                public Map<String, String> loadAll(Iterable<? extends String> keys) throws Exception {
                    return null;
                }
            });

    private final LoadingCache<String, String> refreshCache = Caffeine.newBuilder()
            .refreshAfterWrite(10, TimeUnit.SECONDS)
            .build(k -> k + "不存在,给你默认值1");

    public String get(String key) {

        String value = cache.getIfPresent(key);// null
        cache.get(key);          // default
        cache.getAll(List.of(key));
        return value;

    }


    public String setCache(String key, String value) {

        refreshCache.put(key, value);
        return refreshCache.getIfPresent(key);
    }

    public String getRefresh(String key) {

        return refreshCache.get(key);

    }
}
